#import <objc/runtime.h>
#import "MRAlert.h"

@interface UIAlertView (MRAlert)

@property (nonatomic) AlertHandler	handler;

@end

@implementation UIAlertView (MRAlert)
@dynamic handler;

- (void)setHandler:(AlertHandler)handler
{
	objc_setAssociatedObject(self, @"alertResult", handler, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (AlertHandler)handler
{
	return objc_getAssociatedObject(self, @"alertResult");
}

- (void)dealloc
{
	objc_removeAssociatedObjects(self);
}

@end

#pragma mark - 对话框
/*===================================================================
 自定提示对话框
 ==================================================================*/
@implementation MRAlert
{
	NSTimer		*_timer;
	NSString	*_message;
}

/*===================================================================
 显示对话框
 ==================================================================*/
+ (id)alertWithMessage:(NSString *)message
{
    return [MRAlert alertWithMessage:message other:nil handler:nil];
}

+ (id)alertWithMessage:(NSString *)message handler:(AlertHandler)handler
{
	return [MRAlert alertWithMessage:message other:nil handler:handler];
}

+ (id)alertWithMessage:(NSString *)message other:(NSString *)other handler:(AlertHandler)handler
{
    //自动识别标题
    if (message.length && [[message substringToIndex:1] isEqualToString:@"{"])
    {
        NSRange range = [message rangeOfString:@"}"];
        NSString *title = [message substringWithRange:NSMakeRange(1,range.location-1)];
        
        return [MRAlert alertWithTitle:title message:[message substringFromIndex:range.location+1] other:other handler:handler];
    }
    return [MRAlert alertWithTitle:@"" message:message other:other handler:handler];
}

+ (id)alertWithTitle:(NSString *)title message:(NSString *)message
{
    return [MRAlert alertWithTitle:title message:message other:nil handler:nil];
}

+ (id)alertWithTitle:(NSString *)title message:(NSString *)message handler:(AlertHandler)handler
{
	return [MRAlert alertWithTitle:title message:message other:nil handler:handler];
}

+ (id)alertWithTitle:(NSString *)title message:(NSString *)message other:(id)other handler:(AlertHandler)handler
{
	MRAlert *alert = [[MRAlert alloc] init];
	
	if (IOS8)		//IOS8之后启用新的对话框
	{
		alert->_controller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
		
		//
		[alert.controller addAction:[UIAlertAction actionWithTitle:(other ? @"取消" : @"知道了") style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
			[alert->_timer invalidate];
			if (handler) handler(0);
		}]];
		
		if ([other isKindOfClass:[NSArray class]])
		{
			for (UIAlertAction *action in other)
				[alert.controller addAction:action];
		}
		else if ([other isKindOfClass:[UIAlertAction class]])
		{
			[alert.controller addAction:other];
		}
		else if (other)
		{
			[alert.controller addAction:[UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
				[alert->_timer invalidate];
				if (handler) handler(1);
			}]];
		}
		
		UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
		while (vc.presentedViewController) vc = vc.presentedViewController;
		
		[vc showViewController:alert.controller];
		return alert;
	}
	
	//IOS7的对话框
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:title
												   message:message
												  delegate:nil
										 cancelButtonTitle:other ? @"取消" : @"知道了"
										 otherButtonTitles:nil];
	
    alert->_controller = (UIAlertController *)view;
	
    //其它按钮
    if ([other isKindOfClass:[NSArray class]])
    {
        for (NSString *btn in other)
            [view addButtonWithTitle:btn];
    }
    else if (other)
    {
        [view addButtonWithTitle:other];
    }
    
    view.delegate = alert;
    view.handler  = handler;
    [view show];
	
    return alert;
}

/*===================================================================
 说明:
	延时对话框
 ==================================================================*/
+ (id)delayAlertWithTitle:(NSString *)title message:(NSString *)message other:(id)other handler:(AlertHandler)handler
{
	MRAlert *alert = [MRAlert alertWithTitle:title message:[NSString stringWithFormat:message, 10] other:other handler:handler];
	alert->_message = message;
	alert.delaySecond = 10;
	
	alert->_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:alert selector:@selector(timerProc:) userInfo:nil repeats:YES];
	[[NSRunLoop mainRunLoop] addTimer:alert->_timer forMode:NSRunLoopCommonModes];
	
	return alert;
}

- (void)timerProc:(NSTimer *)timer
{
	if (--self.delaySecond == 0)
	{
		[self dismiss];
	}
}

- (void)setDelaySecond:(NSUInteger)delaySecond
{
	_delaySecond = delaySecond;
	
	id alert = self.controller;
	[alert setMessage:[NSString stringWithFormat:_message, (int)_delaySecond]];
}

- (void)dismiss
{
	[_timer invalidate];
	
	if ([self.controller isKindOfClass:[UIAlertView class]])
		[(UIAlertView *)self.controller dismissWithClickedButtonIndex:0 animated:YES];
	else
		[self.controller cancel];
}

/*===================================================================
 说明:
    结束对话框
 ==================================================================*/
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[_timer invalidate];
	alertView.delegate = nil;
	
    if (alertView.handler) alertView.handler(buttonIndex);
    alertView.handler = nil;
}

@end
